import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Form,
  Input,
  Button,
  Row,
  Col,
  Alert,
  Table,
  Tag,
  Popconfirm,
  Select,
  Icon,
  message,
  Modal,
} from 'antd';
import AxiosUtil from '@/tool/AxiosUtil';
import SetIcon from '@/pages/sys/user/components/SetIcon';
import UserAdd from '@/pages/sys/user/components/UserAdd';
import UserEdit from '@/pages/sys/user/components/UserEdit';

const { Column } = Table;
const { Option } = Select;

/**
 * 用户管理
 *
 * @author zhangby
 * @date 25/11/19 4:40 pm
 */
// eslint-disable-next-line react/prefer-stateless-function
class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: [],
      list: [],
      loading: false,
      isShow: false,
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        defaultPageSize: 10,
        showSizeChanger: true,
        onChange: (page, pageSize) => {
          this.state.query.pageNum = page;
          this.state.query.pageSize = pageSize;
          // eslint-disable-next-line react/no-access-state-in-setstate
          this.setState(this.state);
          this.queryUserList();
        },
        onShowSizeChange: (page, pageSize) => {
          this.state.query.pageNum = page;
          this.state.query.pageSize = pageSize;
          // eslint-disable-next-line react/no-access-state-in-setstate
          this.setState(this.state);
          this.queryUserList();
        },
      },
      query: {
        label: '',
        type: '',
      },
      userTypeList: [],
    };
    this.queryUserList = this.queryUserList.bind(this);
  }

  // 初始化
  componentDidMount() {
    this.queryUserList();
    // 查询用户类型
    AxiosUtil.get('/sys/dict/select/data/role_type')
      .then(res => {
        this.setState({ userTypeList: res.result });
      });
  }

  // 查询用户列表
  // eslint-disable-next-line class-methods-use-this
  queryUserList() {
    this.setState({ loading: true });
    AxiosUtil.get('/sys/user', { ...this.state.query, ...this.props.form.getFieldsValue() })
      .then(res => {
        const val = res.result;
        this.setState({
          pagination: {
            pageSize: val.size,
            current: val.current,
            total: val.total,
          },
          list: val.records,
          loading: false,
        })
      })
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      .catch(err => {
        this.setState({ loading: false });
      })
  }

  // 删除
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  deleteConfirm(id) {
    AxiosUtil.delete(`/sys/user/${id}`)
      .then(() => {
        message.success('删除用户成功');
        this.queryUserList();
      });
  }

  // 批量删除
  // eslint-disable-next-line class-methods-use-this
  deleteBachConfirm() {
    const { rows } = this.state;
    // eslint-disable-next-line no-underscore-dangle
    const _this = this;
    Modal.confirm({
      title: '确定要删除选择的记录吗?',
      content: `已选择${rows.length}项记录。`,
      onOk() {
        AxiosUtil.delete(`/sys/user/${rows.join(',')}`)
          .then(() => {
            message.success('删除用户成功');
            _this.queryUserList();
            _this.setState({ rows: [] });
          });
      },
    });
  }

  // 重置密码
  // eslint-disable-next-line class-methods-use-this
  resetPwdConfirm() {
    const { rows } = this.state;
    // eslint-disable-next-line no-underscore-dangle
    const _this = this;
    Modal.confirm({
      title: '确定要重置密码吗?',
      content: `已选择${rows.length}项记录。`,
      onOk() {
        AxiosUtil.put(`/sys/user/reset/pwd/${rows.join(',')}`)
          .then(() => {
            message.success('重置密码成功');
            _this.queryUserList();
            _this.setState({ rows: [] });
          });
      },
    });
  }

  // eslint-disable-next-line react/sort-comp
  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 6,
        offset: 0,
      },
      wrapperCol: {
        span: 6,
        offset: 0,
      },
    };
    return (
      <div>
        <PageHeaderWrapper>
          <Card>
            <Form layout="inline" {...formItemLayout} style={{ textAlign: 'left' }}>
              <Row gutter={10}>
                <Col xs={24} sm={16} md={12} lg={8}>
                  <Form.Item label="用户名">
                    {getFieldDecorator('name', {})(<Input placeholder="名称" width={220}
                                                          style={{ width: 220 }}/>)}
                  </Form.Item>
                </Col>
                <Col xs={24} sm={16} md={12} lg={8}>
                  <Form.Item label="登录名">
                    {getFieldDecorator('loginName', {})(<Input placeholder="名称" width={220}
                                                               style={{ width: 220 }}/>)}
                  </Form.Item>
                </Col>
                {
                  this.state.isShow ?
                    <div>
                      <Col xs={24} sm={16} md={12} lg={8}>
                        <Form.Item label="联系方式">
                          {getFieldDecorator('mobile', {})(<Input placeholder="名称" width={220}
                                                                  style={{ width: 220 }}/>)}
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={16} md={12} lg={8}>
                        <Form.Item label="&nbsp;&nbsp;邮&nbsp;&nbsp;箱">
                          {getFieldDecorator('email', {})(<Input placeholder="名称" width={220}
                                                                 style={{ width: 220 }}/>)}
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={16} md={12} lg={8}>
                        <Form.Item label="&nbsp;&nbsp;类&nbsp;&nbsp;型">
                          {getFieldDecorator('userType', {
                            initialValue: '',
                          })(
                            <Select style={{ width: 220 }}>
                              <Option value="">全部</Option>
                              {
                                this.state.userTypeList.map((item, key) => (
                                  // eslint-disable-next-line react/no-array-index-key
                                  <Option key={key} value={item.value}>{item.label}</Option>
                                ))
                              }
                            </Select>,
                          )}
                        </Form.Item>
                      </Col>
                    </div>
                    : null
                }
                <Col xs={24} sm={16} md={12} lg={8}>
                  <Form.Item>
                    <Button icon="search" type="primary" onClick={this.queryUserList}>查询</Button>
                  </Form.Item>
                  <Form.Item>
                    {/* eslint-disable-next-line react/no-access-state-in-setstate */}
                    <Button icon={this.state.isShow ? 'up' : 'down'} type="link"
                            onClick={() => this.setState({ isShow: !this.state.isShow })}>
                      {this.state.isShow ? '收起' : '展开'}
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            {/* 功能按钮 */}
            <div style={{ marginTop: 20 }}>
              {/* 新建用户 */}
              <UserAdd queryUserList={this.queryUserList}/>
              {/* 隐藏功能 */}
              {
                this.state.rows.length > 0 ?
                  <span>
                    <Button type="danger" icon="delete" style={{ marginLeft: 10 }}
                            onClick={this.deleteBachConfirm.bind(this)}>批量删除</Button>
                    <Button icon="key" style={{ marginLeft: 10 }}
                            onClick={this.resetPwdConfirm.bind(this)}>重置密码</Button>
                  </span>
                  : null
              }
              <Alert style={{ margin: '20px 0 20px 0' }}
                     message={
                       <div>
                         已选择 <span style={{
                         color: '#1690ff',
                         fontWeight: 600,
                         margin: '0 5px',
                       }}>{this.state.rows.length}</span> 项
                         <span style={{
                           color: '#1690ff',
                           marginLeft: 30,
                           cursor: 'pointer',
                         }} onClick={() => this.setState({ rows: [] })}>清空</span>
                       </div>
                     } type="info" showIcon/>
            </div>
            {/* 列表查询 */}
            <div style={{ marginTop: 30 }}>
              <Table dataSource={this.state.list} scroll={{ x: 900 }} loading={this.state.loading}
                     pagination={this.state.pagination}
                     rowKey="id"
                     rowSelection={{
                       selectedRowKeys: this.state.rows,
                       onChange: selectedRowKeys => {
                         this.setState({ rows: selectedRowKeys })
                       },
                     }}
              >
                <Column width={100} align="center" title="头像" dataIndex="photo"
                        render={this.renderPhoto}/>
                <Column width={100} align="center" title="用户名" dataIndex="name"
                        render={(val, record) => (
                          <UserEdit userId={record.id} queryUserList={this.queryUserList}>
                            <span style={{
                              cursor: 'pointer',
                              color: '#2490ff'
                            }}>{val}</span>
                          </UserEdit>
                        )}/>
                <Column width={100} align="center" title="登录名" dataIndex="loginName"
                        render={this.detailRender}/>
                <Column width={100} align="center" title="部门" dataIndex="tails.officeName"
                        render={this.renderOffice}/>
                <Column width={100} align="center" title="用户类型" dataIndex="tails.userTypeLabel"
                        render={this.renderRole}/>
                <Column width={120} align="center" title="联系方式" dataIndex="mobile"
                        render={this.renderText}/>
                <Column width={120} align="center" title="邮箱" dataIndex="email"
                        render={this.renderText}/>
                <Column width={120} align="center" title="创建时间" dataIndex="createDate"
                        render={this.renderText}/>
                {/* eslint-disable-next-line @typescript-eslint/no-unused-vars */}
                <Column width={200} align="center" title="操作" dataIndex="id" render={id => (
                  <div>
                    <UserEdit userId={id} queryUserList={this.queryUserList}/>
                    {/* 删除 */}
                    <Popconfirm
                      onConfirm={this.deleteConfirm.bind(this, id)}
                      title="确定要删除记录吗？"
                      icon={<Icon type="question-circle-o" style={{ color: 'red' }}/>}
                    >
                      <Button type="danger" shape="circle" icon="delete"/>
                    </Popconfirm>
                  </div>
                )}/>
              </Table>
            </div>
          </Card>
        </PageHeaderWrapper>
      </div>
    )
  }

  // 头像
  // eslint-disable-next-line class-methods-use-this
  renderPhoto(photo) {
    return (
      <div>
        <SetIcon key={photo} photo={photo} size="small"/>
      </div>
    )
  }

  // 创建日期
  // eslint-disable-next-line class-methods-use-this
  renderText(val) {
    return (<Tag.CheckableTag>{val}</Tag.CheckableTag>)
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars,class-methods-use-this
  renderRole(val, record) {
    // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
    return (<Tag color={roleColors[record.userType % 5]}>{val}</Tag>)
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars,class-methods-use-this
  renderOffice(val, record) {
    // eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
    return (<Tag color="volcano">{val}</Tag>)
  }
}

const roleColors = ['red', 'cyan', 'green', 'blue', 'geekblue'];

export default Form.create({ name: 'index' })(index);
